package com.aeric.qrpro;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aeric.CWNetwork.BaseActivity;
import com.aeric.CWUtility.ToastUtil;
import com.aeric.CWDomain.GlobalVariables;
import com.aeric.CWUtility.SharedPreferencesUtils;
import com.aeric.domain.UserInfo;
import com.okhttplib.HttpInfo;
import com.okhttplib.OkHttpUtil;
import com.okhttplib.annotation.CacheType;
import com.okhttplib.callback.Callback;

import java.io.IOException;

/**
 * Created by Administrator on 2016/5/12.
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private Button btn_login;
    private EditText et_phone;
    private EditText et_password;
    private TextView tv_register;
    private RelativeLayout rl_user;
    private ImageView login_picture;
    private  Animation anim,anim2;
    private boolean isNeedDeleteCache = true;
    @Override
    protected int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupActionBar();
        initView();
        setListener();
    }
    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    private void setupActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // Show the Up button in the action bar.
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowCustomEnabled(true);
            actionBar.setTitle(R.string.login);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView(){
        btn_login = (Button) findViewById(R.id.btn_login);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_password = (EditText) findViewById(R.id.et_password);
        tv_register = (TextView) findViewById(R.id.tv_register);
        rl_user = (RelativeLayout) findViewById(R.id.rl_user);
        login_picture = (ImageView) findViewById(R.id.login_picture);
        et_phone.setCursorVisible(false);
        et_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_phone.setCursorVisible(true);
            }
        });
        et_password.setCursorVisible(false);
        et_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_password.setCursorVisible(true);
            }
        });
        anim = AnimationUtils.loadAnimation(this, R.anim.login_anim);
        anim.setFillAfter(true);
        rl_user.startAnimation(anim);

        anim2 = AnimationUtils.loadAnimation(this, R.anim.login_head_anim);
        anim2.setFillAfter(true);
        login_picture.startAnimation(anim2);
    }

    private void setListener(){
        btn_login.setOnClickListener(this);
        tv_register.setOnClickListener(this);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()){
            case R.id.btn_login:
                //登录
                String username = et_phone.getText().toString().trim();
                String password = et_password.getText().toString().trim();
                if (username.equals("")|| password.equals("")){
                  ToastUtil.toastShortTip(LoginActivity.this,"用户名密码必须填写！");
                }else{
                    loginTask(username,password);
                }
                break;
            case R.id.tv_register:
                //跳到注册界面
                intent.setClass(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void loginTask(String username,String password) {
        String url = GlobalVariables.SERVICEURL + "/Qrpro/login";
        getLoadingDialog().showDialog();
        //        String url = "http://api.k780.com:88/?app=life.time&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
        OkHttpUtil.Builder().setCacheType(CacheType.CACHE_THEN_NETWORK).setConnectTimeout(2)
                    .build(this)
                    .doGetAsync(
                            HttpInfo.Builder()
                                    .setUrl(url)
                                    .addParam("userName", username).addParam("password", password)
                                    .build(),
                    new Callback() {
                            @Override
                            public void onSuccess(HttpInfo info) throws IOException {
                                getLoadingDialog().dismiss();
                                String result = info.getRetDetail();
                                ToastUtil.toastLongTip(LoginActivity.this,result);
                                UserInfo p = saveUserInfo("");
                                Intent intent = new Intent();
                                intent.putExtra("userInfo",p);
                                intent.setClass(LoginActivity.this,UserCenterActivity.class);
                                startActivity(intent);
                                finish();
                    }
                            @Override
                            public void onFailure(HttpInfo info) throws IOException {
                                getLoadingDialog().dismiss();
                                ToastUtil.toastShortTip(LoginActivity.this,"亲，网络出现问题，请稍候尝试！");
                                UserInfo p = saveUserInfo("");
                                Intent intent = new Intent();
                                intent.putExtra("userInfo",p);
                                intent.setClass(LoginActivity.this,UserCenterActivity.class);
                                startActivity(intent);
                                finish();
                            }
                        }
                );
        needDeleteCache(true);
    }

    private UserInfo saveUserInfo(String result){
        //实例化一个UserInfo实例，这是我们想要存储到SharedPreferences中的对象
        UserInfo p = new UserInfo("1","LIZHIQ","001");
        SharedPreferencesUtils sp = new SharedPreferencesUtils(this,"User");
        sp.setObject("UserInfo",p);
        return p;
    }

    private void needDeleteCache(boolean delete) {
        isNeedDeleteCache = delete;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
